package com.gopay.bis.citic.micro.operation;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.xml.sax.InputSource;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.DomDriver;


import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 
 * @Description xml-bean转换
 * @author hougn
 * @date 2015年11月23日
 *
 */
public class XmlBeanUtil {

	public static  String toXml(Object obj) {
		// 去掉多一个下划线的问题
		XStream xstream = new XStream(new DomDriver("UTF-8", new NoNameCoder()));
		xstream.processAnnotations(obj.getClass());
		return xstream.toXML(obj);
	}
	
    public static String toXml(Map<String, String> params){
        StringBuilder buf = new StringBuilder();
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        buf.append("<xml>");
        for(String key : keys){
            buf.append("<").append(key).append(">");
            buf.append("<").append(params.get(key)).append(">");
            buf.append("</").append(key).append(">\n");
        }
        buf.append("</xml>");
        return buf.toString();
    }

	/**
	 * 将传入xml文本转换成Java对象
	 * @Title: toBean
	 * @param xmlStr
	 * @param cls xml对应的class类
	 * @return T xml对应的class类的实例对象
	 */
	public static <T> T toBean(String xmlStr, Class<T> cls) {
		XStream xstream = new XStream(new DomDriver("UTF-8"));
		xstream.processAnnotations(cls);
        xstream.ignoreUnknownElements();
        T obj = (T) xstream.fromXML(xmlStr);
		return obj;
	}
	
    public static String parseXML(Map<String, String> map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = map.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if (null != v && !"".equals(v) && !"appkey".equals(k)) {
                sb.append("<" + k + ">" + map.get(k) + "</" + k + ">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
    /** 
     * @Description: 转换退款查询报文
     * @param res
     * @return 
     * @author w_jiqing 
     */
    public static String toRefundQueryXml(String res){
        Map<String,String> map = new HashMap<String, String>();
        try {
           map = toMap(res.getBytes(),"UTF-8");
           Iterator<Entry<String, String>> it =map.entrySet().iterator();
           while(it.hasNext()){
               Map.Entry<String, String> entry =it.next();
               if(entry.getKey().contains("refund")){
                   it.remove();
               }
           }                 
        } catch (Exception e) {
        }
        return parseXML(map);       
    }
	
    /**
     * 转XMLmap
     * @author  
     * @param xmlBytes
     * @param charset
     * @return
     * @throws Exception
     */
    public static Map<String, String> toMap(byte[] xmlBytes,String charset) throws Exception{
        SAXReader reader = new SAXReader(false);
        InputSource source = new InputSource(new ByteArrayInputStream(xmlBytes));
        source.setEncoding(charset);
        Document doc = reader.read(source);
        Map<String, String> params = ElementtoMap(doc.getRootElement());
        return params;
    }
    
    /**
     * 转MAP
     * @author  
     * @param element
     * @return
     */
    public static Map<String, String> ElementtoMap(Element element){
        Map<String, String> rest = new HashMap<String, String>();
        List<Element> els = element.elements();
        for(Element el : els){
            rest.put(el.getName().toLowerCase(), el.getTextTrim());
        }
        return rest;
    }


}
